﻿using SSHTool.Model;
using SSHTool.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Documents;

namespace SSHTool.Service
{
    public class FileService : JsonFileService
    {
        private readonly string file_name = "file_{0}.json";

        private int connectionId = 0;

        public override string FileName => string.Format(file_name, connectionId);

        public FileService UpdateConnectionId(int connectionId)
        {
            this.connectionId = connectionId;

            return this;
        }

        public List<FileModel> GetFileList(int connectionId)
        {
            this.UpdateConnectionId(connectionId);

            var list = GetList<FileModel>();

            if (list == null)
            {
                list = new List<FileModel>();
            }

            return list.OrderBy(m => m.Id).ToList();
        }

        public bool AddFile(int type, string path, string name, IList<FileModel> list)
        {
            if (list == null)
            {
                list = new List<FileModel>();
            }

            var model = list.FirstOrDefault(m => m.Path == path);
            if (model != null)
            {
                return false;
            }

            int maxId = 0;

            if (list.Count > 0)
            {
                maxId = list.Max(m => m.Id);
            }

            maxId++;

            model = new FileModel()
            {
                Id = maxId,
                Type = type,
                Path = path,
                Name = name,
                FileName = FileUtil.GetFileName(path)
            };

            list.Add(model);

            Update(list);

            return false;
        }
    }
}
